<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\imagenew;
use App\photonew;
use DB;

class photoController extends Controller
{
    /**
     * 显示相册的展示
     * @return [type] [description]
     */
    public function getIndex()
    {
        $data = photonew::get();
        return view('xiangce.index',['data' => $data]);
    }

    /**
     * 执行相册的添加
     * @return [type] [description]
     */
    public function postImage(Request $request)
    {
        $this->validate($request, [
            'coverpicture' => 'required',
            'description' => 'required',
            'name' => 'required'
        ]);
        //获取数据
        $data = $request -> except('coverpicture');
        //执行文件上传
        if ($request->hasFile('coverpicture') && $request->file('coverpicture')->isValid()) {
            //获取文件名
            $filename = time().mt_rand(10000,99999);
            $suffix = $request -> file('coverpicture') -> getClientOriginalExtension();
            $newFilename = $filename.'.'.$suffix;
            //文件上传目录
            $upload =  config('app.upload');
            //执行文件上传
            $request -> file('coverpicture') -> move($upload,$newFilename);
            //将文件写入到对象中
            $data['coverpicture'] = trim($upload,'.').$newFilename;

        } else {

           return back() -> with('warning','上传失败');
        }

        $photo = new photonew();  
        // 拼接写入数据库     
        foreach($data as $key => $value) {
            $photo -> $key = $value;
        }
        //判断文件是否上传成功
        if($photo -> save()) {
            return json_encode(['status'=> 1,'msg' => '创建成功']);
        } else {
           return json_encode(['status' => 0, 'msg' => '创建失败']);
        }
    }

    /**
     * 执行相册的编辑
     * @return [type] [description]
     */
    public function postEdit(Request $request,$id)
    {
        $uploadData = $request -> except('_token');
        //获取数据
        $database = photonew::findOrFail($id);
        //执行文件上传
        if ($request ->hasFile('coverpicture') && $request->file('coverpicture')->isValid()) {
            //上传的后缀
            $suffix = $request -> file('coverpicture') -> getClientOriginalExtension();
            //声明上传允许的后缀
            $allowed_extensions = ["png", "jpg", "gif","jpeg"];
            //执行判断
            if (in_array($suffix,$allowed_extensions)) {
                //文件名
                $filename = md5(time()).mt_rand(10000,99999);
                //新文件
                $newFilename = $filename.".$suffix";
                //上传目录
                $upload = config('app.upload');
                //读取原来文件
                $oldCover =  $database -> coverpicture;
                //执行文件的删除
                if(unlink('.'.$oldCover)) {
                   //执行文件上传
                   $request -> file('coverpicture') -> move($upload,$newFilename);
                   //修改上传数据源
                   $uploadData['coverpicture'] = trim($upload,'.').$newFilename;
                } else {
                    return back() -> with('warning','上传失败');
                }
            }  else {
                return back() -> with('danger','上传文件格式不对');
            }
        }

        //遍历数据
        foreach($uploadData as $key => $value) {
            $database -> $key = $value;
        }
        //判断是否上传成功
        if ($database -> save()) {
            return back() -> with('success','编辑成功');
        }
        return back() -> with('warning','编辑失败');        
    }

    /**
     * 执行相册的删除
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function postDelete($id)
    {
        $arr = [];
        //查询图片数据
        $arr[] = DB::table('photonews') 
                 -> where('id',$id) 
                 -> select('photonews.coverpicture') 
                 -> first() -> coverpicture;

        $dataI = DB::table('imagenews') -> where('photos_id',$id) -> select('src') -> get();
        //拼接数组
        foreach($dataI as $value) {
            $arr[] = $value -> src;
        }
        //开始事务
        DB::beginTransaction();

        $resP = DB::table('photonews') -> where('id',$id) -> delete();
        $resI = DB::table('imagenews') -> where('photos_id',$id) -> delete();
        //判断事务的结果
        if ($resP && $resI) {
            DB::commit();
             //执行删除相册图片操作
            foreach($arr as $value) {
               unlink('.'.$value);
            }              
            return redirect('/photo/index') -> with('success','删除成功');
        } else {
            DB::rollBack();
            return back() -> with('warning','上传成功');
        }
    }

    /**
     * 相册的详情
     * @return [type] [description]
     */
    public function getDetail($id)
    {
        //相册中的封面
        $cover = photonew::find($id);
        //相册中的图片
        $data = imagenew::where('photos_id',$id) -> get();
        return view('xiangce.detail',['images' => $data,'cover' => $cover,'coverId' => $id]);
    }

    /**
     * 执行相册上传
     * @return [type] [description]
     */
   public function postDoUpload(Request $request)
   {
        $this->validate($request, [
                'photo' => 'required',
                'intro' => 'required',
                'name' => 'required',
                'photos_id' => 'required'
            ]);
        //声明上传允许的后缀
        $allowed_extensions = ["png", "jpg", "gif","jpeg"];
        //获取上传的数据
        $images = $request -> photo;
        $photos_id = $request -> photos_id;
        $name = $request -> name;
        $intro = $request -> intro;

        if ($request->hasFile('photo')) {
            $arr = [];
            foreach($images as $key => $value) {
                //获得文件的扩展
                $suffix = $value -> getClientOriginalExtension();
                //判断上传的后缀
                if (in_array($suffix,$allowed_extensions)) {

                    //拼接文件名
                    $filename = md5(time()).mt_rand(100000,999999);
                    //重新拼接文件
                    $newfilename = $filename.".$suffix";
                    //获取上传文件的路径
                    $dir = config('app.upload');
                    //执行上传文件
                    $request -> file('photo')[$key] -> move($dir,$newfilename);
                    //拼接入数据库的其他字段
                    $tmp['photos_id'] = $photos_id;
                    $tmp['name'] = $name;
                    $tmp['intro'] = $intro;
                    $tmp['src'] = trim($dir.$newfilename,'.');
                    $arr[] = $tmp;
                }

                continue;
            }

        } else {

            return back() -> with('warning','上传文件失败');
        }
        //执行插入
        $res = DB::table('imagenews') -> insert($arr);
        if($res == 'true') {
             return back() -> with('success','上传成功');
        } else {
             return back() -> with('warning','上传成功');
        }
   }

   /**
    * 执行图片的修改
    * @return [type] [description]
    */
   public function postImageEdit(Request $request,$id)
   {    
        //验证
        $this->validate($request, [
                'intro' => 'required',
                'name' => 'required',
            ]);    
        //获取数据
        $data = $request -> except('_token');
        $database = imagenew::findOrFail($id);
        //遍历数据
        foreach($data as $key => $value) {
           $database -> $key = $value; 
        }
        //执行数据库修改
        if ($database -> save()) {
             return back() -> with('success','修改成功');
        } else {
             return back() -> with('warning','修改失败');
        }
   }

   /**
    * 执行图片的删除
    * @param  [type] $id [description]
    * @return [type]     [description]
    */
   public function postImageDelete($id)
   {
        $data = imagenew::findOrFail($id);
        //获取src
        $deleteSrc = '.'.$data -> src;
        //执行删除
        $res = $data -> delete();
        if ($res) {
             unlink($deleteSrc);
             return back() -> with('success','删除成功');
        } else {
             return back() -> with('warning','删除失败');
        }
   }

}
